#!/usr/bin/env python3
"""
ego

Funtoo's personality tool
"""

# Main ego program.
#
# Copyright 2015-2017 Daniel Robbins and Funtoo Solutions, Inc.
# See LICENSE.txt for terms of distribution.

import configparser
import os
import sys


def join_path(x, y):
	# ignore absolute paths (leading "/") in second component, for convenience...
	if y.startswith("/"):
		return os.path.join(x, y[1:])
	else:
		return os.path.join(x, y)


VERSION = "2.8.7"

settings = configparser.ConfigParser()

if "ROOT" in os.environ:
	root_path = os.environ["ROOT"]
else:
	root_path = "/"

if "EGO_CONFIG" in os.environ:
	settings_path = os.environ["EGO_CONFIG"]
else:
	settings_path = join_path(root_path, "/etc/ego.conf")
try:
	settings.read(settings_path)
except IOError:
	print("Config file %s not found." % settings_path)
	sys.exit(1)
except configparser.Error as e:
	print("Config file error: %s" % e.message)
	sys.exit(1)

file_path = os.path.realpath(__file__)
parent_path = os.path.dirname(file_path)

if os.path.isdir(os.path.join(parent_path, ".git")):
	# we are being run from a git repository; so run in "dev mode", grab modules, etc from git path...
	install_path = parent_path
elif "global" in settings and "install_path" in settings["global"]:
	install_path = settings["global"]["install_path"]
else:
	install_path = "/usr/share/ego"

sys.path.insert(0, install_path + "/python")

from ego.config import EgoConfig

econfig = EgoConfig(settings, settings_path, root_path=root_path, install_path=install_path)

from ego.output import Color, Output
from ego.module import EgoModule, usage

if root_path != "/":
	Output.warning("Using ROOT of %s." % root_path)
	Output.warning("Using ego configuration file %s" % settings_path)

if __name__ == "__main__":
	exec_name = os.path.basename(sys.argv[0])
	action = None
	args = []
	if exec_name != "ego":
		# called as shortcut symlink
		for key, config in econfig.ego_mods_info.items():
			if "shortcut" in config and os.path.basename(config["shortcut"]) == exec_name:
				action = key
				args = sys.argv[1:]
				break
		if not action:
			print(Color.RED + "Unrecognized shortcut %s. Type ego help for more info." % exec_name + Color.END)
			sys.exit(1)
	else:
		# generic help display
		if len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] in ["info", "help"]):
			usage(econfig)
		elif len(sys.argv) == 3 and sys.argv[1] in ["info", "help"]:
			# ego help query, etc.
			mod = sys.argv[2]
			action = sys.argv[1]
			if mod not in econfig.ego_mods:
				print("Module not found: %s. Exiting." % mod)
				sys.exit(1)
			if mod not in econfig.ego_mods_info:
				print("No %s is available for %s ego module." % (action, mod))
			else:
				if action == "info":
					print("Extended information for %s ego module:" % mod)
					for key in econfig.ego_mods_info[mod]:
						print("%20s: %s" % (key, econfig.ego_mods_info[mod][key]))
					print()
				else:
					if "help" in econfig.ego_mods_info[mod]:
						print(econfig.ego_mods_info[mod]["help"])
					else:
						print("No help available for this ego module.")
			action = None
		elif len(sys.argv) >= 2:
			# called as 'ego'
			action = sys.argv[1]
			args = sys.argv[2:]
		else:
			print(Color.RED + "Please specify an action. Type ego help for more info." + Color.END)
			sys.exit(1)
	if action:
		try:
			EgoModule.run_ego_module(action, econfig, args, VERSION)
		except PermissionError:
			Output.fatal("Permissions error -- please make sure you are running this command as the correct user.")
		except KeyboardInterrupt:
			Output.fatal("Interrupted -- exiting.")
		except Exception as e:
			Output.error("Ego encountered an unexpected error: " + e.__class__.__name__)
			try:
				outfile = "/tmp/ego-traceback-%s.txt" % os.getpid()
				with open(outfile, "w") as f:
					import traceback

					f.write(str(e))
					f.write(traceback.format_exc())
				Output.error("Full traceback written to %s." % outfile)
			except (PermissionError, IOError):
				Output.error("Unable to write full traceback.")
			sys.exit(1)
# vim: ts=4 sw=4 noet
